﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using SimpleTools;
using UnityEngine;


public static class Language
{
    private static Dictionary<string, string> Dic;
    private static readonly string LanguagePath = @"Configs\Language\";

    /// <summary>
    /// 当前所被选择的语言
    /// </summary>
    public static string NowLanguage = "zh";
    /// <summary>
    /// 首次加载游戏从资源库中提取文件，第二次加载游戏从本地读取文件
    /// </summary>
    static Language()
    {
        NowLanguage = SaveData._.language;
        var text = FileHelp.GetStringData(Application.dataPath + LanguagePath + NowLanguage);
        if (text==null)
        {
        var textAsset = Resources.Load<TextAsset>(LanguagePath+NowLanguage);
        FileHelp.SaveStringData(Application.dataPath + LanguagePath + NowLanguage, textAsset.text);//开发用
        Dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(textAsset.text);
        }
        else
        {
            Dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(text);
        }
    }

    public static void SetLanguage(string languageName)
    {
        NowLanguage = languageName;
        

        var textAsset = Resources.Load<TextAsset>(LanguagePath + NowLanguage);
        if (textAsset==null)
        {
            textAsset = Resources.Load<TextAsset>(LanguagePath + "zh");
        }
        Dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(textAsset.text);
        
        SaveData._.language = NowLanguage;
        SaveData.Save();

    }

    /// <summary>
    /// 获取符合当前语言的文字
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    public static string Get(string key)
    {
        string back=null;
        Dic.TryGetValue(key, out back);
        if (back==null)
        {
            back = key;
#if UNITY_EDITOR
            Dic.Add(key, key);
            FileHelp.SaveStringData(Application.dataPath + LanguagePath + NowLanguage, JsonConvert.SerializeObject(Dic));
#endif
        }
        return back;
    }


}
